package com.link.base.base.projectmanage.service;

import com.link.base.base.message.push.service.PushService;
import com.link.base.base.projectmanage.dao.mybatis.mapper.CarRegisterMapper;
import com.link.base.base.projectmanage.model.CarRegBusManagerInter;
import com.link.base.base.projectmanage.model.CarRegister;
import com.link.base.base.projectmanage.model.PartRegister;
import com.link.base.base.projectmanage.model.TaskInfo;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.DateUtil;
import com.link.core.util.LovUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 车型登记-
 *
 * @author 刘启鑫
 * @date 2020/09/11 14:43
 */
@Service
public class CarRegisterServiceImpl extends BasicServiceImpl<CarRegister> implements CarRegisterService {

    @Resource
    private CarRegisterMapper carRegisterMapper;

    @Resource
    private PartRegisterService partRegisterService;

    @Resource
    private CarRegBusManagerInterService carRegBusManagerInterService;

    @Resource
    private TaskInfoService taskInfoService;

    @Resource
    private PushService pushService;

    @Override
    public BasicMapper<CarRegister> getBasicMapper() {
        return carRegisterMapper;
    }


    @Override
    public void beforInsert(CarRegister entity) throws Exception {
        super.beforInsert(entity);
        // 新建时默认表单状态为未提交
//        entity.setFormStatus(ConsUtils.Project.FormStatus.UN_SUBMITED);

        //新建一个车型登记，插入九条拜访计划到拜访表
        //1.新建拜访计划实体，放入当前车型登记头id
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setCarHeadId(entity.getId());
        String[] stage = {
            "BefPacked6Mon", "BefPacked3Mon","BefPacked1Mon","RFIGet","SyncDesign", "RFQGet","QuoteStage","CompetitorAnalysis","FixedPhase"};
        //2.for循环，依次插入拜访阶段
        for (int i = 0; i < 9; i++) {
            //新建拜访计划，赋值拜访头ID
            taskInfo.setId(keyGenerateService.keyGenerate());
            taskInfo.setCurrentStage(stage[i]);
            //发包前6个月、发包前3个月、发包前1个月”时，根据车型头信息“预计发包时间”预制
            //1.拿到车型头预计发包时间，将字符串解析为日期格式parse
            Calendar estSendPackge = Calendar.getInstance();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

            if (i == 0) {
                estSendPackge.setTime(df.parse(entity.getEstSendPackTime()));
                //2.回退六个月
                estSendPackge.add(Calendar.MONTH, -6);
                //3.拿到回退时间，将日期格式化为日期/时间字符串format
                String estStart = df.format(estSendPackge.getTime());
                taskInfo.setEstStartDate(estStart);
            } else if (i == 1) {
                estSendPackge.setTime(df.parse(entity.getEstSendPackTime()));
                //2.回退3个月
                estSendPackge.add(Calendar.MONTH, -3);
                //3.拿到回退时间，将日期格式化为日期/时间字符串format
                String estStart = df.format(estSendPackge.getTime());
                taskInfo.setEstStartDate(estStart);
            } else if (i == 2) {
                estSendPackge.setTime(df.parse(entity.getEstSendPackTime()));
                //2.回退1个月
                estSendPackge.add(Calendar.MONTH, -1);
                //3.拿到回退时间，将日期格式化为日期/时间字符串format
                String estStart = df.format(estSendPackge.getTime());
                taskInfo.setEstStartDate(estStart);
            } else {
                taskInfo.setEstStartDate(null);
            }
            taskInfoService.insert(taskInfo);
        }
    }

    /**
     * 编辑车型信息，保存后更新拜访计划预计开始时间
     * @param entity
     * @throws Exception
     */
    @Override
    public void beforUpdate(CarRegister entity) throws Exception {
        super.beforUpdate(entity);
        //根据当前车型头发包时间，对应更新拜访计划预计开始时间
        //查询头的所有拜访计划，更新阶段为"BefPacked6Mon", "BefPacked3Mon","BefPacked1Mon"的预计开始时间
        TaskInfo task = new TaskInfo();
        task.setCarHeadId(entity.getId());
        List<TaskInfo> taskInfos = taskInfoService.queryAll(task);
        String[] stage = {"BefPacked6Mon", "BefPacked3Mon","BefPacked1Mon"};
        //1.拿到车型头预计发包时间，将字符串解析为日期格式parse
        Calendar estSendPackge = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        for (TaskInfo taskInfo : taskInfos) {
            if (stage[0].equals(taskInfo.getCurrentStage())) {
                estSendPackge.setTime(df.parse(entity.getEstSendPackTime()));
                //2.回退六个月
                estSendPackge.add(Calendar.MONTH, -6);
                //3.拿到回退时间，将日期格式化为日期/时间字符串format
                String estStart = df.format(estSendPackge.getTime());
                taskInfo.setEstStartDate(estStart);
                taskInfoService.update(taskInfo);
                continue;
            } else if (stage[1].equals(taskInfo.getCurrentStage())) {
                estSendPackge.setTime(df.parse(entity.getEstSendPackTime()));
                //2.回退3个月
                estSendPackge.add(Calendar.MONTH, -3);
                //3.拿到回退时间，将日期格式化为日期/时间字符串format
                String estStart = df.format(estSendPackge.getTime());
                taskInfo.setEstStartDate(estStart);
                taskInfoService.update(taskInfo);
                continue;
            } else if (stage[2].equals(taskInfo.getCurrentStage())) {
                estSendPackge.setTime(df.parse(entity.getEstSendPackTime()));
                //2.回退1个月
                estSendPackge.add(Calendar.MONTH, -1);
                //3.拿到回退时间，将日期格式化为日期/时间字符串format
                String estStart = df.format(estSendPackge.getTime());
                taskInfo.setEstStartDate(estStart);
                taskInfoService.update(taskInfo);
                continue;
            } else {
                continue;
            }
        }
    }

    @Override
    public void beforUpsert(CarRegister entity) throws Exception {
        super.beforUpsert(entity);
        //预计总寿命 =  预计量产结束时间 - 预计量产开始时间
        String prodStart = entity.getExpBatchProdStart();
        String prodEnd = entity.getExpBatchProdEnd();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date prodStart1 = df.parse(prodStart);
        Date prodEnd1 = df.parse(prodEnd);
        Long c = prodEnd1.getTime() - prodStart1.getTime();
        double day = c / (1000 * 60 * 60 * 24);
        double year = day / 365;
        entity.setEstLife(String.valueOf(year));
        //保存车型头，校验是否为生效客户
        // 用equals方法比较的是字符串的内容是否相同
        /*if ( !"Active".equals(entity.getAcctStatus())) {
            throw new ServiceException("IYUCARREG-001");
        }*/
    }

    @Override
    public void deleteCascadeById(CarRegister entity) throws Exception {
        carRegisterMapper.deleteCascadeById(entity);
    }

    @Override
    public void beforDelete(CarRegister entity) throws Exception {
        super.beforDelete(entity);
        entity = carRegisterMapper.queryByIdWithPart(entity);
        if (!Objects.isNull(entity)) {
            List<PartRegister> partRegisterList = entity.getPartRegisters();
            List<CarRegBusManagerInter> carRegBusManagerInterList = entity.getCarRegBusManagerInters();
            if (!CollectionUtils.isEmpty(partRegisterList)) {
                for (PartRegister partRegister: partRegisterList) {
                    partRegisterService.deleteById(partRegister);
                }
            }
            if (!CollectionUtils.isEmpty(carRegBusManagerInterList)) {
                for (CarRegBusManagerInter carRegBusManagerInter: carRegBusManagerInterList) {
                    carRegBusManagerInterService.deleteById(carRegBusManagerInter);
                }
            }
        }
    }

    @Override
    public void carRegisterVisit() throws Exception {
        //功能背景：当商务人员进行拜访计划的制定时，会填写字段“预计开始时间”。此时系统会根据预计开始时间的值进行提醒设置。
        //功能说明：当商务人员成功保存拜访计划后，根据字段“预计开始时间”的值提前七天做预警提示。同时校验实际开始时间，若实际开始时间有值，则关闭提醒功能。
        //提示语句为“您的XX（XX为项目号）项目于X年X月X日（预计开始时间）有阶段为XX阶段（当前阶段）的拜访计划需要进行，请及时处理”

        //1.查询所有车型对应的拜访计划，判断每个拜访计划是否有预计开始时间
        CarRegister carRegister = new CarRegister();
        List<CarRegister> carRegisters = carRegisterMapper.queryAll(carRegister);
        TaskInfo taskInfo = new TaskInfo();
        for (CarRegister carRegister1 : carRegisters) {
            taskInfo.setCarHeadId(carRegister1.getId());
            taskInfo.setAttr4("ActStartDateIsNull");  //查询没有实际开始时间的拜访计划，旨在减少循环次数
            List<TaskInfo> taskInfos = taskInfoService.queryAll(taskInfo);
            for (TaskInfo taskInfo1 : taskInfos) {
                if (taskInfo1.getEstStartDate() != null) {
                    //获取当前系统时间
                    Date date = new Date();
                    //简单日期格式
//                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //将taskInfo1.getEstStartDate() 的字符串String解析成data
                    Date parseEstStartDate = DateUtil.DATETIME_FORMATTER.parse(taskInfo1.getEstStartDate());
//                    Date date1 = df.parse(taskInfo1.getEstStartDate());
                    Date estStartDate = new Date(parseEstStartDate.getTime() - 7 * 24 * 60 * 60 * 1000);
                    //当前阶段 值列表源码转换
                    String est = LovUtil.getLovName("LNK_CURRENT_STAGE", taskInfo1.getCurrentStage());
                    String carType = carRegister1.getCarType() == null ? "" : carRegister1.getCarType();
                    String message = "您有客户：" + carRegister1.getAccntName() + "，车型为"  + carType + "的车型预算工作，于" + taskInfo1.getEstStartDate()
                            + "有阶段为" + est + "的拜访计划需要进行，请及时处理";
                    //判断今天是否在预计开始日期前第七天 之后，对本项目的每一个拜访计划做提醒
                    if (taskInfo1.getActStartDate() == null && estStartDate.before(date)) {
                        sendPushNotice(taskInfo1.getId(),carRegister1.getId(),message,taskInfo1.getCreatedBy());
                    }
                } else {
                    break;
                }
            }
        }
    }


    /**
     * 发送系统消息
     *
     * @author NingLanhao
     * @param businessId   预警对象数据的row_id，如消费者id、拜访id
     * @param alertId      头ID
     * @param message 预警消息
     * @param userId       发送对象
     * @return void
     * @date 2019-10-09 14:14
     */
    private void sendPushNotice(Long businessId, Long alertId, String message, Long userId) throws Exception {
        // 发送消息 预警的系统消息里objectId保存预警记录id
        pushService.sampleMessageForModule(message, userId, businessId, "CarRegisterVisit");
    }


    @Override
    public List<CarRegister> querySalemanById(CarRegister car) {
        return carRegisterMapper.querySalemanById(car);
    }

    /**
     * 车型预算信息表（列表） 报表
     * @author 王昊
     * @date 2021/05/06
     */
    @Override
    public List<CarRegister> carRegisterReport(CarRegister entity) throws Exception {
        return carRegisterMapper.carRegisterReportPage(entity);
    }
}

